use anyhow::{Context, Result};
use serde::{Deserialize, Serialize};
use std::path::PathBuf;
use tokio::fs;

#[derive(Debug, Deserialize, Serialize, Clone)]
pub struct ServerConfig {
    pub host: String,
    pub port: u16,
    pub domain: String,
    pub upload_secret: Option<String>,
}

#[derive(Debug, Deserialize, Serialize, Clone)]
pub struct MirrorConfig {
    pub upstream_url: String,
    pub sync_interval: u64,
    pub distributions: Vec<String>,
    pub architectures: Vec<String>,
}

#[derive(Debug, Deserialize, Serialize, Clone)]
pub struct StorageConfig {
    pub root_path: PathBuf,
    pub incoming_path: PathBuf,
    pub gpg_key_path: PathBuf,
    pub gpg_private_key_path: PathBuf,
}

#[derive(Debug, Deserialize, Serialize, Clone)]
pub struct Config {
    pub server: ServerConfig,
    pub mirror: MirrorConfig,
    pub storage: StorageConfig,
}

impl Config {
    pub async fn load_or_create(path: &str) -> Result<Self> {
        if let Ok(config) = fs::read_to_string(path).await {
            let config: Config = toml::from_str(&config)
                .with_context(|| format!("解析配置文件失败: {}", path))?;
            return Ok(config);
        }
        
        // 创建默认配置
        let default_config = Config {
            server: ServerConfig {
                host: "0.0.0.0".to_string(),
                port: 8080,
                domain: "localhost:8080".to_string(),
                upload_secret: Some("change-me-to-a-secret-key".to_string()),
            },
            mirror: MirrorConfig {
                upstream_url: "https://packages.termux.dev/apt/termux-main".to_string(),
                sync_interval: 3600,
                distributions: vec!["stable".to_string()],
                architectures: vec!["aarch64".to_string(), "arm".to_string(), 
                                   "i686".to_string(), "x86_64".to_string()],
            },
            storage: StorageConfig {
                root_path: PathBuf::from("./repo"),
                incoming_path: PathBuf::from("./incoming"),
                gpg_key_path: PathBuf::from("./keys/termux-mirror.asc"),
                gpg_private_key_path: PathBuf::from("./keys/termux-mirror-private.asc"),
            },
        };
        
        // 保存默认配置
        let config_str = toml::to_string_pretty(&default_config)?;
        fs::write(path, config_str).await?;
        
        log::warn!("已创建默认配置文件: {}", path);
        log::warn!("请编辑配置文件并设置您的域名和密钥");
        
        Ok(default_config)
    }
}